use Component;

package InputManager;

@ISA = qw/Component/;


use constant DEFAULT_BINDINGS => "PLAYER_BASIC";


sub new{
    my $class = shift;
    my $self = {};

    bless $self, $class;
    $self->init(@_);

    return $self;
}

sub init{
    my $self = shift;
    $self->dependencies(qw/KeyboardController LogManager/);

    
    $self->{BINDINGS}->{PLAYER_BASIC} = {
	'h' => 'Left',
	'k' => 'Up',
	'j' => 'Down',
	'l' => 'Right',
	'b' => 'Build',
	's' => 'Spawn',
	'q' => 'Quit'
    };

    $self->{BINDINGS}->{MENU_BASIC} = {
	'h' => 'Left',
	'k' => 'Up',
	'j' => 'Down',
	'l' => 'Right',

	'y' => 'Yes',
	'n' => 'No',

	'c' => 'Cancel',

	'q' => 'Quit'
    };

    $self->{BINDINGS_STACK} = [];

    $self->{ACTIVE_BINDINGS} = $self->{"BINDINGS"}->{(DEFAULT_BINDINGS)};
    push @{$self->{BINDINGS_STACK}}, DEFAULT_BINDINGS;
}

sub chooseBindings{
    my $self = shift;

    my $newBindingsKey = shift;
    return 0 unless(defined $newBindingsKey);

    my $newBindings = $self->{BINDINGS}->{$newBindingsKey};
    return 0 unless(defined $newBindings);

    $self->{ACTIVE_BINDINGS} = $newBindings;

    return 1;
}

sub pushBindings{
    my $self = shift;
    my $newBindingsKey = shift;

    if($self->chooseBindings($newBindingsKey)){
	push @{$self->{BINDINGS_STACK}}, $newBindingsKey;
    }
    
}


sub popBindings{
    my $self = shift;
    my $stackLen = scalar(@{$self->{BINDINGS_STACK}});
    if($stackLen == 0){
	$self->pushBindings(DEFAULT_BINDINGS);
    }else{
	my $currBindings = pop @{$self->{BINDINGS_STACK}};
	my $newBindings = $self->{BINDINGS_STACK}->[$stackLen-2];

	$self->chooseBindings($newBindings);
    }
    
}


sub waitForKeyCommand{
    my $self = shift;
    my $key = $self->{KeyboardController}->waitForKey;

    my $commandName = $self->{ACTIVE_BINDINGS}->{$key};
    return $commandName if(defined $commandName);
    return 0;
}

sub waitForKeyCommandFromList{
    my $self = shift;
    my $validCommands_array_ref = shift;
    my @validCommands_array = @{$validCommands_array_ref};
    my %validCommands = ();

    $lm = $self->{LogManager};
    $lm->log("Waiting for commands: ".(join ",", @validCommands_array));

    foreach(@validCommands_array){
	$lm->log($_);
	$validCommands{$_} = 1;
    }

    my $command = undef;
    my $waiting = 1;

    while($waiting){
	$command = $self->waitForKeyCommand();
	$lm->log("COMMAND RECEIVED: ".$command);
	if($validCommands{$command}){
	    $lm->log("It's valid");
	    return $command;
	}
    }

    return 0;
}


1;


